Page({
  data: {
    statusBarHeight: 0,
    navbarHeight: 0,
    accountBalance: 1200.00,      // 账户余额
    withdrawableAmount: 1000.00,  // 可提现金额
    withdrawalAmount: '',          // 提现金额
    taxAmount: 0,                 // 个人所得税
    showTaxModal: false,          // 是否显示税务提示弹窗
    showWithdrawableTipModal: false, // 是否显示可提现金额说明弹窗
    invoiceOption: 'no',          // 发票选项：'no' 不提供，'yes' 提供
    invoiceImage: '',             // 发票图片
    minWithdrawal: 100,           // 最低提现金额
    taxThreshold: 800,            // 个人所得税起征点
    formattedAccountBalance: '1200.00',
    formattedWithdrawableAmount: '1000.00',
    formattedTaxAmount: '0.00',
    hasShownTaxModal: false       // 是否已经显示过税务弹窗（避免重复弹出）
  },

  onLoad() {
    // 获取系统信息，用于适配状态栏高度
    try {
      const systemInfo = wx.getSystemInfoSync()
      const statusBarHeight = systemInfo.statusBarHeight || 0
      const navbarHeight = statusBarHeight + 44
      this.setData({
        statusBarHeight: statusBarHeight,
        navbarHeight: navbarHeight
      })
    } catch (e) {
      console.error('获取系统信息失败:', e)
      this.setData({
        statusBarHeight: 0,
        navbarHeight: 44
      })
    }

    this.loadWalletInfo()
  },

  loadWalletInfo() {
    // 从本地存储或全局数据加载钱包信息
    const app = getApp()
    const walletInfo = wx.getStorageSync('walletInfo')
    
    if (walletInfo) {
      const balance = walletInfo.balance || 1200.00
      const withdrawable = walletInfo.withdrawableAmount || 1000.00
      this.setData({
        accountBalance: balance,
        withdrawableAmount: withdrawable,
        formattedAccountBalance: balance.toFixed(2),
        formattedWithdrawableAmount: withdrawable.toFixed(2)
      })
    } else {
      // 使用默认值
      this.setData({
        accountBalance: 1200.00,
        withdrawableAmount: 1000.00,
        formattedAccountBalance: '1200.00',
        formattedWithdrawableAmount: '1000.00'
      })
    }
  },

  // 全部提现
  withdrawAll() {
    const amount = this.data.withdrawableAmount
    this.setData({
      withdrawalAmount: amount.toFixed(2)
    })
    this.calculateTax()
    
    // 如果可提现金额大于800，自动弹出税务提示弹窗
    if (amount > this.data.taxThreshold) {
      setTimeout(() => {
        this.setData({
          showTaxModal: true,
          hasShownTaxModal: true
        })
      }, 300)
    }
  },

  // 输入提现金额
  onAmountInput(e) {
    const value = e.detail.value
    // 只允许输入数字和小数点
    const amount = value.replace(/[^\d.]/g, '')
    
    // 限制最大提现金额
    let finalAmount = parseFloat(amount) || 0
    if (finalAmount > this.data.withdrawableAmount) {
      finalAmount = this.data.withdrawableAmount
    }
    
    // 保存之前的金额，用于判断是否从小于等于800变为大于800
    const previousAmount = parseFloat(this.data.withdrawalAmount) || 0
    const wasAboveThreshold = previousAmount > this.data.taxThreshold
    const isAboveThreshold = finalAmount > this.data.taxThreshold
    
    // 先更新金额
    this.setData({
      withdrawalAmount: finalAmount > 0 ? finalAmount.toString() : ''
    })
    
    this.calculateTax()
    
    // 如果金额从小于等于800变为大于800，自动弹出税务提示弹窗
    if (isAboveThreshold && !wasAboveThreshold && !this.data.showTaxModal) {
      // 延迟一下，确保输入完成后再弹出
      setTimeout(() => {
        this.setData({
          showTaxModal: true,
          hasShownTaxModal: true
        })
      }, 500)
    }
    
    // 如果金额小于等于800，关闭弹窗并重置标志
    if (!isAboveThreshold && this.data.showTaxModal) {
      this.setData({
        hasShownTaxModal: false,
        showTaxModal: false,
        invoiceOption: 'no',
        invoiceImage: ''
      })
    }
  },

  // 计算个人所得税
  calculateTax() {
    const amount = parseFloat(this.data.withdrawalAmount) || 0
    let taxAmount = 0
    
    // 如果金额大于800，需要扣除个人所得税
    if (amount > this.data.taxThreshold) {
      // 个人所得税计算：超过800的部分按20%计算
      taxAmount = (amount - this.data.taxThreshold) * 0.2
    }
    
    // 始终显示个人所得税（即使为0也显示）
    this.setData({
      taxAmount: taxAmount,
      formattedTaxAmount: taxAmount.toFixed(2)
    })
  },

  // 提现
  submitWithdrawal() {
    const amount = parseFloat(this.data.withdrawalAmount) || 0
    
    // 验证提现金额
    if (!amount || amount <= 0) {
      wx.showToast({
        title: '请输入提现金额',
        icon: 'none'
      })
      return
    }
    
    if (amount < this.data.minWithdrawal) {
      wx.showToast({
        title: `最低提现金额为${this.data.minWithdrawal}元`,
        icon: 'none'
      })
      return
    }
    
    if (amount > this.data.withdrawableAmount) {
      wx.showToast({
        title: '提现金额不能超过可提现金额',
        icon: 'none'
      })
      return
    }
    
    // 如果金额大于800，显示税务提示弹窗
    if (amount > this.data.taxThreshold) {
      this.setData({
        showTaxModal: true
      })
    } else {
      // 直接提交提现
      this.doWithdrawal()
    }
  },

  // 执行提现
  doWithdrawal() {
    const amount = parseFloat(this.data.withdrawalAmount) || 0
    const taxAmount = this.data.taxAmount
    const actualAmount = amount - taxAmount
    
    // 显示确认信息
    let confirmText = `提现金额: ${amount.toFixed(2)}元\n`
    if (taxAmount > 0) {
      confirmText += `个人所得税: ${taxAmount.toFixed(2)}元\n`
      confirmText += `实际到账: ${actualAmount.toFixed(2)}元`
    }
    
    wx.showModal({
      title: '确认提现',
      content: confirmText,
      success: (res) => {
        if (res.confirm) {
          // 如果选择提供发票，需要上传发票
          if (this.data.invoiceOption === 'yes' && amount > this.data.taxThreshold) {
            if (!this.data.invoiceImage) {
              wx.showToast({
                title: '请上传发票',
                icon: 'none'
              })
              return
            }
          }
          
          // 执行提现操作
          this.processWithdrawal(amount, taxAmount, actualAmount)
        }
      }
    })
  },

  // 处理提现
  processWithdrawal(amount, taxAmount, actualAmount) {
    wx.showLoading({
      title: '处理中...',
      mask: true
    })
    
    // 模拟提现处理
    setTimeout(() => {
      wx.hideLoading()
      
      // 更新钱包余额
      const app = getApp()
      const walletInfo = wx.getStorageSync('walletInfo') || {}
      const newBalance = (this.data.accountBalance - amount).toFixed(2)
      const newWithdrawable = (this.data.withdrawableAmount - amount).toFixed(2)
      
      walletInfo.balance = parseFloat(newBalance)
      walletInfo.withdrawableAmount = parseFloat(newWithdrawable)
      wx.setStorageSync('walletInfo', walletInfo)
      
      // 添加提现记录到交易记录
      const transactions = wx.getStorageSync('walletTransactions') || []
      transactions.unshift({
        id: Date.now(),
        type: 'withdraw',
        amount: -amount,
        taxAmount: taxAmount,
        actualAmount: actualAmount,
        date: new Date().toLocaleString('zh-CN'),
        status: 'processing', // processing, success, failed
        tab: 'expense'
      })
      wx.setStorageSync('walletTransactions', transactions)
      
      wx.showToast({
        title: '提现申请已提交',
        icon: 'success',
        duration: 2000
      })
      
      setTimeout(() => {
        wx.navigateBack()
      }, 2000)
    }, 1500)
  },

  // 选择发票选项
  selectInvoiceOption(e) {
    const option = e.currentTarget.dataset.option
    this.setData({
      invoiceOption: option
    })
    
    // 如果选择不提供发票，清空发票图片
    if (option === 'no') {
      this.setData({
        invoiceImage: ''
      })
    }
  },

  // 上传发票
  uploadInvoice() {
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFilePaths[0]
        
        // 这里应该上传到服务器，现在先保存本地路径
        this.setData({
          invoiceImage: tempFilePath
        })
        
        wx.showToast({
          title: '发票上传成功',
          icon: 'success'
        })
      },
      fail: (err) => {
        console.error('选择图片失败:', err)
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        })
      }
    })
  },

  // 查看发票
  viewInvoice() {
    if (this.data.invoiceImage) {
      wx.previewImage({
        urls: [this.data.invoiceImage],
        current: this.data.invoiceImage
      })
    }
  },

  // 删除发票
  deleteInvoice() {
    this.setData({
      invoiceImage: ''
    })
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 确认税务弹窗
  confirmTaxModal() {
    if (this.data.invoiceOption === 'yes' && !this.data.invoiceImage) {
      wx.showToast({
        title: '请上传发票',
        icon: 'none'
      })
      return
    }
    
    this.setData({
      showTaxModal: false
    })
    
    // 提交提现
    this.doWithdrawal()
  },

  // 关闭税务弹窗
  closeTaxModal() {
    this.setData({
      showTaxModal: false,
      invoiceOption: 'no',
      invoiceImage: ''
    })
    // 注意：不重置 hasShownTaxModal，避免重复弹出
  },

  // 查看提现规则
  goToWithdrawalRules() {
    // 如果弹窗打开，先关闭弹窗
    if (this.data.showTaxModal) {
      this.setData({
        showTaxModal: false
      })
    }
    // 跳转到提现规则页面
    wx.navigateTo({
      url: '/pages/withdrawal-rules/withdrawal-rules'
    })
  },

  // 显示可提现金额说明
  showWithdrawableTip() {
    this.setData({
      showWithdrawableTipModal: true
    })
  },

  // 关闭可提现金额说明弹窗
  closeWithdrawableTipModal() {
    this.setData({
      showWithdrawableTipModal: false
    })
  },

  // 返回
  goBack() {
    const pages = getCurrentPages()
    if (pages.length > 1) {
      wx.navigateBack()
    } else {
      wx.navigateTo({
        url: '/pages/my-wallet/my-wallet'
      })
    }
  }
})

